<template>
	<view>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" type="bottom">
			<!-- <view class="posterImg"> -->
			<view class="radius-8 overflow-auto flex justify-center">
				<!-- <slot></slot> -->
				<canvas :style="{ width: cW + 'px', height: cH + 'px' }" canvas-id="myPoster"></canvas>
			</view>

			<view class="flex item-center justify-between mx-10">
				<button class="w50 h-46 flex center radius-8 bg-primary text-white fs-16 font-normal text-center mx-0 my-10" @click="saveImage">保存海报</button>
				<!-- open-type='share' -->
				<button v-if="props.show=='merchant'" class="w50 h-46 flex center radius-8 bg-primary text-white fs-16 font-normal text-center mx-0 mt-0" style="background:#16BE62;" @click="downLoadFile">分享好友</button>
				<button v-else open-type='share' :data-filePath="tempFilePath" class="w50 h-46 flex center radius-8 bg-primary text-white fs-16 font-normal text-center mx-0 mt-0" style="background:#16BE62;">分享好友</button>
			</view>
			<view class="w-full mt-20 flex justify-center">
				<image src="@/static/svg/icon-close.svg" mode="widthFix" class="icon-close"
					style="width: 40px;" @click="showPopPoster(false)"></image>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		watch,
		ref,
		getCurrentInstance,
		defineEmits
	} from 'vue'
	import {  drawRoundImg, drawRoundedRect, getSystem, textPrewrap } from '@/utils/canvasUtil.js'
	import { useUserStore } from '@/stores/modules/user.js'
	const popup = ref()
	const props = defineProps({
		inviteData: {
			type: Object//海报参数
		},
		show:{
			type:String
		},
		groupData: {
			type: [Object, null]
		},
	})

	const userStore = useUserStore()
	const emit = defineEmits(['emitImg'])
	const tempFilePath = ref('')
	const buildImg = () => {
		//判断用户授权
		uni.getSetting({
		   success(res) {
			  // console.log('获取用户权限',res.authSetting)
			  if(Object.keys(res.authSetting).length>0){
				  //判断是否有相册权限
				  if(res.authSetting['scope.writePhotosAlbum']==undefined){
					  //打开设置权限
					  uni.openSetting({
						success(res) {
						  console.log('设置权限',res.authSetting)
						}
					  })
				  }else{
					  if(!res.authSetting['scope.writePhotosAlbum']){
						  //打开设置权限
						  uni.openSetting({
							success(res) {
							  console.log('设置权限',res.authSetting)
							}
						  })
					  }
				  }
			  }else{
				  return
			  }
		   }
		})
		uni.canvasToTempFilePath({
			canvasId: 'myPoster',
			quality: 1,
			complete: (res) => {
				console.log(res,'ddd')
				tempFilePath.value = res.tempFilePath

				// console.log('保存到相册',res.tempFilePath);
				// emit('emitImg',res.tempFilePath)
			}
		},instance);
	}
	const downLoadFile = () => {
			// <!-- https://api.huodongtg.com/斗拱平台综合支付服务协议代运营补充协议.docx -->
		// uni.downloadFile({
		// 	url: tempFilePath.value, //仅为示例，并非真实的资源
		// 	success: (res) => {
		// 		if (res.statusCode === 200) {
		// 			console.log('下载成功');

		// 		}
		// 	}
		// });
		wx.showShareImageMenu({
			path: tempFilePath.value,
			name:(props.show=='merchant'?'邀请你入驻火动成为他的商户' :'邀请你成为他的经纪人')+'.png',
			success() {},
			fail: console.error,
		})
	}
	//获取图片
	const getImageInfo = (imgSrc) =>{
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: imgSrc,
				success: (image) => {
					resolve(image);
					console.log('获取图片成功',image)
				},
				fail: (err) => {
					reject(err);
					console.log('获取图片失败',err)
				}
			});
		});
	}
	

	const instance = getCurrentInstance()
	const { w, h, scale } = getSystem()
	//圆角矩形
	const drawRoundRect = (ctx, x, y, width, height, radius, color) =>{
		// console.log(ctx)
		ctx.save();
		ctx.beginPath();
		ctx.setFillStyle(color);
		ctx.setStrokeStyle(color)
		ctx.setLineJoin('round');  //交点设置成圆角
		ctx.setLineWidth(radius);
		ctx.strokeRect(x + radius/2, y + radius/2, width - radius , height - radius );
		ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2);
		ctx.stroke();
		ctx.closePath();
	}
	//初始化画布
	const cH = ref(480* scale)
	const cW = ref(375* scale)
	const __init = async () =>{
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		let ctx = uni.createCanvasContext('myPoster',instance)
		// width: 304px; height: 404px;
		// console.log(ctx,)
		let canvasW = cW.value;
		let canvasH = cH.value;
		// console.log(ctx,canvasW,canvasH)
		//设置画布背景透明
		
		// ctx.fillStyle = '#ffffff'
		// ctx.setFillStyle('#FFFFFF')
		// ctx.fillRect(0,0,canvasW,canvasH)
		// 绘制渐变背景
		// let gradient = ctx.createCircularGradient(0, 0, canvasW)
		// gradient.addColorStop(0, '#F7D6D2') // #D8230A26
		// gradient.addColorStop(1, 'white')
		// // 绘制圆角背景
		// // drawRoundRect(ctx, 0, 0, canvasW, canvasH,0,gradient)
		// drawRoundedRect(ctx, 0, 0, canvasW, canvasH, {
		// 	leftTop: true,
		// 	leftBottom: true,
		// 	rightTop: true,
		// 	rightBottom: true,
		// 	fillColor: gradient,
		// 	r: 8 * scale
		// })
		if(props.show=='merchant'){
			// 获取背景图片
			let bgImg = await getImageInfo('https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/merchant-bg.png')
			drawRoundImg(ctx, bgImg.path, 0, 0, canvasW, canvasH, 0)
			
			let headerW = 36 * scale
			// 获取标题图片
			let headerImg = await getImageInfo(props.inviteData.logo)
			//绘制头像
			drawRoundImg(ctx, headerImg.path, (canvasW - headerW - 8 * scale) / 2, 206 * scale, headerW, headerW, 6 * scale)
			
			let str = props.inviteData.businessShortName.length > 16 ? props.inviteData.businessShortName.substring(0, 16) + '...' : props.inviteData.businessShortName
			let str1 = str, str2 = ''
			if(str.length > 9){
				str1 = str.substring(0, 9)
				str2 = str.substring(9)
			}
			ctx.font = 'normal bold 12px Arial,sans-serif'
			ctx.setFontSize(12*scale)
			ctx.setFillStyle('#333333');
			let str1Width = ctx.measureText(str1 + '').width
			let str2Width = ctx.measureText(str2 + '').width
			str1 && ctx.fillText(str1, ((canvasW - str1Width * scale - 8 * scale) / 2), 262 * scale)
			str2 && ctx.fillText(str2, ((canvasW - str2Width * scale - 8 * scale) / 2), 276 * scale)
			
			//小程序码
			let pathW=100*scale
			let qrcodeImg = await getImageInfo(props.inviteData.miniImgUrl)
			drawRoundImg(ctx, qrcodeImg.path, (canvasW - pathW - 8 * scale) / 2, 288 * scale, pathW, pathW, 0)
			
			if(userStore.userInfo.businessInfo && userStore.userInfo.businessInfo.posterShowAvatarState === 1){
				const avatar = await getImageInfo(userStore.userInfo.businessInfo.logo)
				drawRoundImg(ctx, avatar.path, (canvasW - pathW - 8 * scale) / 2 + 30 * scale, 318 * scale, 43 * scale, 43 * scale, 22 * scale)
			}
		}else{
			// 获取背景图片
			let bgImg = await getImageInfo('https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/poster-bg.png')
			drawRoundImg(ctx, bgImg.path, 0, 0, canvasW, canvasH, 0)
			
			// 获取标题图片
			let headerImg = await getImageInfo(props.inviteData.logo)
			let str = props.inviteData.businessShortName.length > 10 ? props.inviteData.businessShortName.substring(0, 10) + '...' : props.inviteData.businessShortName
			ctx.setFontSize(16*scale)
			let nameWidth = ctx.measureText(str + '').width
			let headerW = 24 * scale
			//绘制头像
			drawRoundImg(ctx, headerImg.path, ((canvasW - headerW - nameWidth * scale) / 2), 176 * scale, headerW, headerW, 6 * scale)
			//绘制商家名称
			ctx.setFillStyle('#333333');
			// let sWidth = ctx.measureText(props.inviteData.businessShortName).width
			ctx.fillText(str, ((canvasW - nameWidth * scale + headerW + 10 * scale) / 2), 194 * scale)
			
			//绘制标题
			// ctx.font = 'normal bold 20px Arial,sans-serif '
			// ctx.setFontSize(22* scale); //设置标题字体大小
			// ctx.setFillStyle('#333333'); //设置标题文本颜色
			// let firTitle = props.show=='merchant'?'"邀请你入驻火动成为他的商户"' : '"邀请你成为他的经纪人"'
			// let tWidth = ctx.measureText(firTitle).width
			
			// ctx.fillText(firTitle, ((canvasW-tWidth) / 2),(234 * scale))
			//绘制价格
			ctx.font = 'normal normal 14px Arial,sans-serif '
			ctx.setFontSize(14* scale);
			ctx.setFillStyle('#000000');
			if(props.groupData && props.groupData.defaultState !== 2){
				let groupNameWidth = ctx.measureText(props.groupData.groupName + '').width
				ctx.fillText(props.groupData.groupName, ((canvasW - groupNameWidth * scale) / 2), 258 * scale)
			}
			// let secTitle = props.show=='merchant'?'合作共赢 无限可能' :'品牌口碑由您来打造'
			// let minTWidth = ctx.measureText(secTitle).width
			let mintH = (88 * scale + 180* scale)
			// ctx.fillText(secTitle,((canvasW-minTWidth) / 2),mintH)
			//小程序码
			let pathW=116*scale
			let qrcodeImg = await getImageInfo(props.inviteData.miniImgUrl)
			drawRoundImg(ctx, qrcodeImg.path, ((canvasW-pathW) / 2),mintH, pathW, pathW, 8* scale)
			// ctx.drawImage(qrcodeImg.path,((canvasW-pathW) / 2),(mintH + 30* scale), pathW, pathW)
			//提示文案
			// ctx.setFontSize(12* scale);
			// let cordTWidth = ctx.measureText('长按识别小程序 接受邀请').width
			// ctx.setFillStyle('rgba(245, 245, 245, 1)')
			// ctx.fillRect(((canvasW-cordTWidth) / 2)-4* scale,(mintH + 60* scale + pathW)-16* scale,cordTWidth + 8* scale,24* scale)
			// ctx.textBaseline = 'center';
			// ctx.setFillStyle('rgba(51, 51, 51, 0.6)');
			// ctx.fillText('长按识别小程序 接受邀请',((canvasW-cordTWidth) / 2),mintH + 60* scale + pathW)
			if(userStore.userInfo.businessInfo && userStore.userInfo.businessInfo.posterShowAvatarState === 1){
				const avatar = await getImageInfo(userStore.userInfo.businessInfo.logo)
				drawRoundImg(ctx, avatar.path, (canvasW-pathW) / 2 + 32 * scale, mintH + 32 * scale, 52 * scale, 52 * scale, 27 * scale)
			}
		}
		//延迟渲染
		setTimeout(()=>{
			ctx.draw(true,()=>{
				uni.hideLoading()
				buildImg()
			})
		},500)
	}
	const showPopPoster = (value) => {
		if (value) {
			popup.value && popup.value.open('center')
			if(props.inviteData){
				__init()
			}
		} else {
			popup.value && popup.value.close()
		}
	}
	watch(()=>props.inviteData,(val) =>{
		if(val){
			__init()
		}
	})
	const saveImage = () => {
		//判断用户授权
		uni.getSetting({
		   success(res) {
			  console.log('获取用户权限',res.authSetting)
			  if(Object.keys(res.authSetting).length>0){
				  //判断是否有相册权限
				  if(res.authSetting['scope.writePhotosAlbum']==undefined){
					  //打开设置权限
					  uni.openSetting({
						success(res) {
						  console.log('设置权限',res.authSetting)
						}
					  })
				  }else{
					  if(!res.authSetting['scope.writePhotosAlbum']){
						  //打开设置权限
						  uni.openSetting({
							success(res) {
							  console.log('设置权限',res.authSetting)
							}
						  })
					  }
				  }
			  }else{
				  return
			  }
		   }
		})
		uni.canvasToTempFilePath({
			canvasId: 'myPoster',
			quality: 1,
			complete: (res) => {
				console.log('保存到相册',res);
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success(res) {
						uni.showToast({
							title: '已保存到相册',
							icon: 'success',
							duration: 2000
						})
						setTimeout(()=>{
							// that.isShow = false
						},2000)
					}
				})
			}
		},instance);
	}

	defineExpose({
		showPopPoster
	})
</script>
<style scoped lang="scss">
	.posterImg{
		padding: 10px;
		border-radius: 8px;
		background-color: #ffffff;
	}
</style>